package com.whatech.mall.order.mq.producer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.whatech.mall.order.model.dto.messaging.OrderAddBonusMessageDTO;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Rabbit 消息生产者。
 */
@Component
public class RabbitProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 发送下单加积分消息。
     *
     * @param addBonusMessageDTO 加积分消息DTO
     */
    public void sendOrderAddBonusMessage(OrderAddBonusMessageDTO addBonusMessageDTO) {
        try {
            // 以订单ID作为消息唯一ID
            CorrelationData correlationData = new CorrelationData();
            correlationData.setId(addBonusMessageDTO.getOrderId() + "");
            // 发送消息
            this.rabbitTemplate.convertAndSend(
                    "order-exchange",                              // Exchange
                    "order.addBonus",                             // Routing Key
                    objectMapper.writeValueAsString(addBonusMessageDTO),      // 消息体内容
                    correlationData                                           // 消息唯一ID
            );
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

}
